﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuditWeb.Models;
using System.IO;
using System.IO.Compression;
using AuditModel;
using System.Reflection;
using System.Drawing;
using DoddleReport.Web;
using DoddleReport;
using System.Globalization;

namespace AuditWeb.Controllers
{
    //[Authorize]
    public class ReportController : Controller
    {
        IAnnualEventBL iaebl = new AnnualEventBL();
        IArchiveBL abl = new ArchiveBL();
        private AuditDBEntities db = new AuditDBEntities();
        ICandidateQuotaBL icqbl = new CandidateQuotaBL();
        IScoreBL isbl = new ScoreBL();
        //
        // GET: /Export/

        [Authorize(Roles = "评委,管理员,区县管理员,学科组组长")]
        public ActionResult Archives(string eventid, string county, string subject, string archiveid)
        {
            //prepare params
            AnnualEvent currentevent;
            string annualeventid = "";
            if (string.IsNullOrEmpty(eventid))
            {
                currentevent= iaebl.GetActiveEvents().FirstOrDefault();//get default activated event
                annualeventid = currentevent.ID;
            }
            else
            {
                annualeventid = eventid; 
                currentevent = iaebl.GetAnnualEvent(annualeventid);
            }

            county = county == null ? "" : county.Trim();
            int _subjectid;
            int.TryParse(subject, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            
            
            archiveid = archiveid == null ? "" : archiveid.Trim();

            if (User.IsInRole("评委"))//get expertjudge's subjectid
            {
                string serialnumber = User.Identity.Name;
                ExpertJudge ej = db.ExpertJudges.SingleOrDefault(e => e.SerialNumber == User.Identity.Name);
                _subjectid = ej.SubjectID.Value;
            }
            if (User.IsInRole("学科组组长"))//get expertjudge's subjectid
            {
                _subjectid = (int)HttpContext.Profile["SubjectId"];
            }
            if (User.IsInRole("区县管理员"))
            {
                county = HttpContext.Profile["CountyCode"].ToString();
            }

            //prepare view model
            AdminArchiveModel aam = new AdminArchiveModel() { AnnualEventId = annualeventid, CountyCode = county, ArchiveId = archiveid, SubjctId = _subjectid };

            var archives = abl.GetArchives(annualeventid, archiveid, _subjectid, county);//db.Archives.Include("AnnualEvent").Include("Subject").Include("County").Include("Teacher");

            ViewBag.AnnualEvent = currentevent;
            ViewBag.AnnualEventId = annualeventid;
            ViewBag.Archives = archives.ToList();
            ViewBag.SelectedIndex = "3";

            //prepare dropdownlist options
            
            if(User.IsInRole("管理员"))//get all data
            {
                ViewBag.County = new SelectList(db.Counties.ToList(), "Code", "Name", county);
                ViewBag.Subject = new SelectList(Helpers.GetActiveSubjects(annualeventid), "Id", "Name", _subjectid);
            }
            else if(User.IsInRole("评委")||User.IsInRole("学科组组长"))//get 1 subject and all counties
            {
                ViewBag.County = new SelectList(db.Counties.ToList(), "Code", "Name", county);
                ViewBag.Subject = new SelectList((from s in db.Subjects.ToList() where s.Id==_subjectid select s) , "Id", "Name", _subjectid);
            }
            else if (User.IsInRole("区县管理员"))//get 1 county and all subjects
            {
                ViewBag.County = new SelectList((from c in db.Counties.ToList() where c.Code==county select c), "Code", "Name", county);
                ViewBag.Subject = new SelectList(Helpers.GetActiveSubjects(annualeventid), "Id", "Name", _subjectid);
            }
            

            //get properties for checkboxes
            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(AuditWeb.Models.ArchiveDisplayer).GetProperties();
            ViewBag.Properties = propertyInfos.ToList();

            //get posted checkbox values
            List<string> columns = new List<string>();
            string sc = Request.Form.ToString();
            string[] nv = sc.Split('&');
            //string datetype = Request.Form["DateType"];
            //DateTime date = DateTime.Parse(Request.Form["Date"]);
            foreach (string ss in nv)
            {
                if (ss.Split('=').Count() > 1)
                {
                    string columnname = ss.Split('=')[0];
                    string v = ss.Split('=')[1];
                    if (v == "true")
                    {
                        columns.Add(columnname);
                    }
                }
            }
            if (columns.Count == 0)
            {
                columns = (new string[] { "ID", "CountyCode", "TeacherName","SubjectID", "ClassTitle", "SchoolName", "GradeLevel", "SchoolAddress" }).ToList();
            }
            ViewBag.ChosenColumns = columns.ToArray();
            
            return View(aam);
        }

        public void ScoreReport()
        {
            Response.Redirect("~/Report/ReportForm1.aspx");
        }

        public ReportResult SaveExcel(string eventid, string county, string subject, string archiveid,string columns)
        {
            //prepare params
            AnnualEvent currentevent;
            string annualeventid = "";
            if (string.IsNullOrEmpty(eventid))
            {
                currentevent = iaebl.GetActiveEvents().FirstOrDefault();
                annualeventid = currentevent.ID;
            }
            else
            {
                annualeventid = eventid;
                currentevent = iaebl.GetAnnualEvent(annualeventid);
            }

            county = county == null ? "" : county.Trim();
            int _subjectid;
            int.TryParse(subject, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            archiveid = archiveid == null ? "" : archiveid.Trim();

            //create format provider for output
            //CultureInfo culture = new CultureInfo("ja-JP");


            //get report source
            var real_archives = abl.GetArchives(annualeventid, archiveid, _subjectid, county);//db.Archives.Include("AnnualEvent").Include("Subject").Include("County").Include("Teacher");
            List<ArchiveDisplayer> archives = new List<ArchiveDisplayer>();
            foreach (var a in real_archives)
            {
                ArchiveDisplayer ad = new ArchiveDisplayer()
                {
                     AnnualEventID=a.AnnualEventID,
                     Attachment1LessonPlan=a.Attachment1LessonPlan,
                     Attachment2Explanation=a.Attachment2Explanation,
                     Birthdate=a.Birthdate!=null?a.Birthdate.Value.Date.ToString("yyyy/M"):"",
                     ClassDate = a.ClassDate!=null?a.ClassDate.Value.Date.ToString("yyyy/MM/d"):"",
                     ClassTime=a.ClassTime!=null?a.ClassTime.Value.ToString("t"):"",
                     ClassTitle=a.ClassTitle,
                     CountyCode=a.County.Name,
                     CountyEBComment=a.CountyEBComment,
                     CountyComment=a.CountyComment,
                     EducationDegree=a.EducationDegree,
                     Gender=a.Gender,
                     GradeLevel=a.GradeLevel,
                     ID=a.ID,
                     PhoneNumber=a.PhoneNumber, 
                     SchoolAddress=a.SchoolAddress,
                     SchoolComment=a.SchoolComment,
                     SchoolName=a.SchoolName,
                     SchoolPrincipal=a.SchoolPrincipal,
                     SubjectID=a.Subject.Name,
                     TeacherName=a.TeacherName,
                     TeachingYears=a.TeachingYears.ToString()
                };
                archives.Add(ad);
            }


            //generate report
            //to use ToReportSource, you must have the class in Dynamic folder
            var report = new DoddleReport.Report(archives.ToReportSource());

            //get property info for headertext
            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(AuditWeb.Models.ArchiveDisplayer).GetProperties();

            //format value


            //hide all columns and set display name for each column if there is a displayname
            foreach (var field in report.DataFields)
            {
                field.Hidden = true;
                try
                {
                    PropertyInfo pi = (from p in propertyInfos where p.Name == field.Name select p).SingleOrDefault();
                    field.HeaderText = Helpers.getDisplayName(pi);
                }
                catch
                {
                }
            }
            
            //only show selected columns
            string[] columns_a = columns.Split('|');

            foreach (string column in columns_a)
            {
                report.DataFields[column].Hidden = false;
            }

            //return report. The report format will decided by the url extension name
            //
            // Try the following sample URLs:
            //
            //  http://localhost:X/doddle/ProductReport.html
            //  http://localhost:X/doddle/ProductReport.txt
            //  http://localhost:X/doddle/ProductReport.xls
            //  http://localhost:X/doddle/ProductReport.xlsx (Requires DoddleReport.OpenXml)
            //  http://localhost:X/doddle/ProductReport.pdf (Requires DoddleReport.iTextSharp or DoddleReport.AbcPdf)
            //  
            return new ReportResult(report);
        }

        [Authorize(Roles = "管理员")]
        public ReportResult ScoreLogs(string subject, string archiveid, string serialnumber)
        {
            //prepare params
            AnnualEvent currentevent = iaebl.GetActiveEvents().FirstOrDefault();
            string annualeventid = currentevent.ID;

            int _subjectid;
            int.TryParse(subject, out _subjectid);
            _subjectid = _subjectid <= 0 ? -1 : _subjectid;
            serialnumber = string.IsNullOrEmpty(serialnumber) ? "" : serialnumber;
            archiveid = string.IsNullOrEmpty(archiveid) ? "" : archiveid;

            //get report source
            var  real_scorelogs = isbl.GetScores(annualeventid, _subjectid, serialnumber, archiveid);
            List<ScoreDisplayer> scorelogs = new List<ScoreDisplayer>();

            //rebuild score list for excel
            foreach (var rs in real_scorelogs)
            {
                ScoreDisplayer sd = new ScoreDisplayer()
                {
                    ArchiveID=rs.ArchiveID,
                    ExpertJudgeSerialNumber=rs.ExpertJudgeSerialNumber,
                    MaterialScore=rs.MaterialScore.Value,
                    InstructionScore=rs.MaterialScore.Value,
                    DefenseScore=rs.DefenseScore.Value,
                    OtherScore = rs.OtherScore.Value,
                    TotalScore = rs.TotalScore.Value,
                    SubmitTime = rs.SubmitTime.Value,
                    Subject=rs.Archive.Subject.Name
                };
                scorelogs.Add(sd);
            }

            //generate report
            //to use ToReportSource, you must have the class in Dynamic folder
            var report = new DoddleReport.Report(scorelogs.ToReportSource());

            //get property info for headertext
            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(AuditWeb.Models.ScoreDisplayer).GetProperties();

            //hide all columns and set display name for each column if there is a displayname
            foreach (var field in report.DataFields)
            {
                field.Hidden = true;
                try
                {
                    PropertyInfo pi = (from p in propertyInfos where p.Name == field.Name select p).SingleOrDefault();
                    field.HeaderText = Helpers.getDisplayName(pi);
                    field.Hidden = false;
                }
                catch
                {
                }
            }


            //return report. The report format will decided by the url extension name
            //
            // Try the following sample URLs:
            //
            //  http://localhost:X/doddle/ProductReport.html
            //  http://localhost:X/doddle/ProductReport.txt
            //  http://localhost:X/doddle/ProductReport.xls
            //  http://localhost:X/doddle/ProductReport.xlsx (Requires DoddleReport.OpenXml)
            //  http://localhost:X/doddle/ProductReport.pdf (Requires DoddleReport.iTextSharp or DoddleReport.AbcPdf)
            //  
            return new ReportResult(report);
        }
    }
}
